package com.fenghongzhang.day010;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class Main2Activity extends AppCompatActivity {
    private Button btn;
    private WebView web;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);


        btn = (Button) findViewById(R.id.btn);
        web = (WebView) findViewById(R.id.web);

        //加载本地的页面
        web.loadUrl("file:///android_asset/index.html");

        //设置支持
        WebSettings settings = web.getSettings();
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setJavaScriptEnabled(true);


        web.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }
        });


        web.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            /**
             * 拦截页面中的js弹框
             * @param view
             * @param url
             * @param message
             * @param result
             * @return
             */
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                Toast.makeText(Main2Activity.this, message, Toast.LENGTH_SHORT).show();
                //多次调用
                result.cancel();
                //拦截网页本身的对话框
                return true;
            }
        });

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //调用js的方法
                web.loadUrl("javascript:call1()");
            }
        });


        //添加一个js的接口
        web.addJavascriptInterface(this,"android");


    }

    public void btn1(View view) {
        String s = "dafa";
        web.loadUrl("javascript:call2('"+s+"')");
    }

    @JavascriptInterface
    public void test(){
        Toast.makeText(this, "测试", Toast.LENGTH_SHORT).show();
    }

    @JavascriptInterface
    public void test1(String s){
        Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
    }
}
